<template>
  <div class="chart-card">
    <h3>资产分类统计</h3>
    <div class="chart-container">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onUnmounted, computed, watchEffect} from 'vue';
import * as echarts from 'echarts';
import { getAssetData } from '@/api/Chart';

const chartRef = ref(null);
let chartInstance: echarts.ECharts | null = null;

// 响应式数据源
const assetData = ref([]);

// 格式转换函数
const formatChartData = (data) => {
  const categories = data.map(item => item.categoryName);
  const statusTypes = ['闲置',  '领用中','使用中', '维修中',  '已报废', '其他'];
  const seriesData = statusTypes.map(status => ({
    name: status,
    type: 'bar',
    stack: 'total',
    data: data.map(item => 
      item.statusDetails.find(detail => detail.status === status)?.count || 0
    )
  }));

  return { categories, seriesData };
};

onMounted(async () => {
  try {
    const res = await getAssetData();
    if (res.code === 200) {
      const { categories, seriesData } = formatChartData(res.data);
      assetData.value = { categories, seriesData };

      if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value);

        // 动态计算配置项
        const getOption = () => ({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: assetData.value.seriesData.map(series => series.name)
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: assetData.value.categories
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },

          series: assetData.value.seriesData
        });

        // 初始渲染
        chartInstance.setOption(getOption());

        // 监听数据变化
        const updateChart = () => {
          chartInstance.setOption(getOption());
        };

        // 创建响应式依赖
        const stop = watchEffect(updateChart);

        // 处理窗口大小变化
        const resizeHandler = () => chartInstance.resize();
        window.addEventListener('resize', resizeHandler);

        // 清理函数
        onUnmounted(() => {
          window.removeEventListener('resize', resizeHandler);
          stop();
          if (chartInstance) {
            chartInstance.dispose();
          }
        });
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
});
</script>

<style scoped>
.chart-card {
  width: 100%;
  max-width: 680px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 15px auto;
}

.chart-card h3 {
  font-size: 18px;
  font-weight: bold;
  padding-left: 16px;
  text-align: left;
}

.chart {
  width: 100%;
  height: 520px;
}
</style>